using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace Pong
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D fond, barres, balle;
        Rectangle barreBleue = new Rectangle(0, 0, 32, 128),
            barreRouge = new Rectangle(32, 0, 32, 128);
        int bleueY, rougeY, bleueX, rougeX;
        Vector2 ballePosition;
        Vector2 balleVitesse = Vector2.Zero;
        int screenWidth, screenHeight;
        float rapportWidth, rapportHeight;
        int scoreBleu = 0,
            scoreRouge = 0;

        KeyboardState keyboard;
        float tempsEcoule;
        int deplacement;

        AudioEngine moteurSonore;
        WaveBank banqueWaves;
        SoundBank banqueSons;

        bool started = false, newGame = false;

        int width = 1280,
            height = 720;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            graphics.PreferredBackBufferHeight = height;
            graphics.PreferredBackBufferWidth = width;
            graphics.ApplyChanges();

            screenWidth = graphics.GraphicsDevice.Viewport.Width;
            screenHeight = graphics.GraphicsDevice.Viewport.Height;

            rapportWidth = screenWidth / 1024.0f;
            rapportHeight = screenHeight / (screenHeight / (float)screenWidth * 1024.0f);

            bleueY = (int)((screenHeight / 2) - (barreBleue.Height / 2) * rapportHeight);
            rougeY = bleueY;

            bleueX = (int)((screenWidth * 0.05) - (barreBleue.Width / 2) * rapportWidth);
            rougeX = (int)((screenWidth * 0.95) - (barreRouge.Width / 2) * rapportWidth);

            ballePosition.X = (screenWidth / 2) - (32 / 2) * rapportWidth;
            ballePosition.Y = (screenHeight / 2) - (32 / 2) * rapportHeight;

            moteurSonore = new AudioEngine("Content/Pong.xgs");
            banqueWaves = new WaveBank(moteurSonore, "Content/Wave Bank.xwb");
            if (banqueWaves != null)
                banqueSons = new SoundBank(moteurSonore, "Content/Sound Bank.xsb");

            this.IsFixedTimeStep = false;

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            fond = Content.Load<Texture2D>("Textures/fond_herbe");
            barres = Content.Load<Texture2D>("Textures/bars");
            balle = Content.Load<Texture2D>("Textures/balle");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            keyboard = Keyboard.GetState();

            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || keyboard.IsKeyDown(Keys.Escape))
                this.Exit();

            tempsEcoule = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000.0f;
            deplacement = (int)((screenHeight / 0.45) * tempsEcoule);

            if (keyboard.IsKeyDown(Keys.D) || GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y < -0.5f)
                bleueY += deplacement;
            else if (keyboard.IsKeyDown(Keys.E) || GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y > 0.5f)
                bleueY -= deplacement;

            if (keyboard.IsKeyDown(Keys.Down) || GamePad.GetState(PlayerIndex.Two).ThumbSticks.Left.Y < -0.5f)
                rougeY += deplacement;
            else if (keyboard.IsKeyDown(Keys.Up) || GamePad.GetState(PlayerIndex.Two).ThumbSticks.Left.Y > 0.5f)
                rougeY -= deplacement;

            if (bleueY < 0)
                bleueY = 0;
            else if (bleueY > screenHeight - (int)(barreBleue.Height * rapportHeight))
                bleueY = screenHeight - (int)(barreBleue.Height * rapportHeight);

            if (rougeY < 0)
                rougeY = 0;
            else if (rougeY > screenHeight - (int)(barreRouge.Height * rapportHeight))
                rougeY = screenHeight - (int)(barreRouge.Height * rapportHeight);

            ballePosition += balleVitesse * tempsEcoule;

            if (ballePosition.Y < 0)
            {
                balleVitesse.Y = -balleVitesse.Y;
                banqueSons.PlayCue("rebond");
            }
            else if (ballePosition.Y > screenHeight - (int)(balle.Height * rapportHeight))
            {
                balleVitesse.Y = -balleVitesse.Y;
                banqueSons.PlayCue("rebond");
            }

            BoundingBox balleBox = new BoundingBox(
                new Vector3(ballePosition.X, ballePosition.Y, 0),
                new Vector3(ballePosition.X + balle.Width * rapportWidth, ballePosition.Y + balle.Height * rapportHeight, 0));
            BoundingBox barreBleueBox = new BoundingBox(
                new Vector3(bleueX, bleueY, 0),
                new Vector3(bleueX + barreBleue.Width * rapportWidth, bleueY + barreBleue.Height * rapportHeight, 0));
            BoundingBox barreRougeBox = new BoundingBox(
                new Vector3(rougeX, rougeY, 0),
                new Vector3(rougeX + barreRouge.Width * rapportWidth, rougeY + barreRouge.Height * rapportHeight, 0));

            if (balleBox.Intersects(barreBleueBox) || balleBox.Intersects(barreRougeBox))
            {
                balleVitesse.X = -balleVitesse.X;
                balleVitesse += balleVitesse * 0.05f;
                banqueSons.PlayCue("rebond");
            }

            if (!started && keyboard.IsKeyDown(Keys.Space) || newGame)
            {
                ballePosition.X = (screenWidth / 2) - (32 / 2) * rapportWidth;
                ballePosition.Y = (screenHeight / 2) - (32 / 2) * rapportHeight;
                started = true;
                newGame = false;
                Random rand = new Random();
                int n = rand.Next(4);
                int vitesseX = (int)(400 * rapportWidth);
                int vitesseY = (int)(400 * rapportHeight);
                switch (n)
                {
                    case 0: balleVitesse = new Vector2(vitesseX, vitesseY); break;
                    case 1: balleVitesse = new Vector2(vitesseX, -vitesseY); break;
                    case 2: balleVitesse = new Vector2(-vitesseX, vitesseY); break;
                    case 3: balleVitesse = new Vector2(-vitesseX, -vitesseY); break;
                }
            }

            if (ballePosition.X < 0)
            {
                scoreRouge++;
                newGame = true;
                banqueSons.PlayCue("but");
            }
            else if (ballePosition.X > screenWidth)
            {
                scoreBleu++;
                newGame = true;
                banqueSons.PlayCue("but");
            }

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            spriteBatch.Draw(fond, new Rectangle(0, 0, screenWidth, screenHeight), Color.White);
            spriteBatch.End();
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null);
            spriteBatch.Draw(barres, new Rectangle(bleueX, bleueY, (int)(barreBleue.Width * rapportWidth), (int)(barreBleue.Height * rapportHeight)), barreBleue, Color.White);
            spriteBatch.Draw(barres, new Rectangle(rougeX, rougeY, (int)(barreRouge.Width * rapportWidth), (int)(barreRouge.Height * rapportHeight)), barreRouge, Color.White);
            spriteBatch.Draw(balle, new Rectangle((int)ballePosition.X, (int)ballePosition.Y, (int)(balle.Width * rapportWidth), (int)(balle.Height * rapportHeight)), new Rectangle(0, 0, balle.Width, balle.Height), Color.White);
            spriteBatch.End();

            Window.Title = "Pong : " + scoreBleu.ToString() + " - " + scoreRouge.ToString();

            base.Draw(gameTime);
        }
    }
}